package cn.growthgate.fgo.interceptor;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.HandlerInterceptor;

import cn.growthgate.fgo.util.CollectionUtils;
import cn.growthgate.fgo.util.DateUtils;
import cn.growthgate.fgo.util.RequestUtils;
import cn.growthgate.fgo.util.StringUtils;

/**
 * 打印请求信息拦截器
 * 
 * @author GrowthGate
 * @since 2019年4月9日
 *
 */
public class PrintRequestInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if (handler instanceof HandlerMethod) {
			String nowTime = DateUtils.toString(new Date(), DateUtils.DEFAULT_DATETIME);
			Method method = ((HandlerMethod) handler).getMethod();
			Map<String, String[]> paramMap = request.getParameterMap();
			StringBuilder msg = new StringBuilder();
			
			msg.append("\n══ ").append(nowTime).append(" ══");
			msg.append("\nip: ").append(RequestUtils.getIp(request));
			msg.append("\nRequestUrI: ").append(request.getRequestURI());
			msg.append("\nController: ").append(method.getDeclaringClass().getName()).append(" (")
					.append(method.getDeclaringClass().getSimpleName()).append(".java:1)");
			msg.append("\nMethod:     ").append(method.getName());
			msg.append("\nHttpMethod: ").append(request.getMethod());
			if (CollectionUtils.isNotEmpty(paramMap)) {
				msg.append("\nParams:");
				for (Entry<String, String[]> entry : paramMap.entrySet()) {
					String[] value = entry.getValue();
					
					msg.append("\n    ").append(entry.getKey()).append("=");
					if (StringUtils.equalsAny(entry.getKey(), "password", "repass")) {
						// 如果请求参数为密码，则不明文显示
						for (int i = 0; i < value.length; i++) {
							value[i] = value[i].replaceAll("\\s|\\S", "*");
						}
					}
					if (value.length == 1) {
						msg.append(value[0]);
					} else {
						msg.append(Arrays.toString(value));
					}
				}
			}
			if (request instanceof MultipartHttpServletRequest) {
				MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
				Iterator<String> iterator = multipartRequest.getFileNames();
				while (iterator.hasNext()) {
					String name = iterator.next();
					List<MultipartFile> files = multipartRequest.getFiles(name);
					
					msg.append("\n    ").append(name).append("=");
					if (files.size() == 1) {
						msg.append(files.get(0).getOriginalFilename());
					} else {
						List<String> filenames = new ArrayList<>(files.size());
						files.forEach(file -> filenames.add(file.getOriginalFilename()));
						msg.append(filenames);
					}
				}
			}
			msg.append("\n═════════════════════");
			System.out.println(msg);
		}
		return true;
	}
	
}
